﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebNext.Domain.Entities;
using System.Web.Mvc;
using System.Xml.Serialization;
using WebNext.Domain;
using WebNext.UI.Properties;
using WebNext.UI.Utils;

namespace WebNext.UI.Models.Entries
{
	public class EntryImageElementViewModel : EntryElementViewModel
	{
		public override EntryElementType Type
		{
			get { return EntryElementType.Image; }
		}

		public string Title
		{
			get;
			private set;
		}

		public bool IsTitleValid
		{
			get;
			private set;
		}

		public string ImageUri
		{
			get;
			set;
		}

		public bool IsImageUriValid
		{
			get;
			set;
		}

		public EntryImageElementViewModel(EntryImageElement entryImageElement) : base(entryImageElement.Order)
		{
			this.Title = entryImageElement.Title;
			this.ImageUri = entryImageElement.ImageUri;
			this.IsTitleValid = true;
			this.IsImageUriValid = true;
		}

		public EntryImageElementViewModel(int order, IDictionary<string, string> properties) : base(order)
		{
			if (properties.ContainsKey("imageTitle"))
			{
				this.Title = properties["imageTitle"];
			}
			
			if (properties.ContainsKey("imageUri"))
			{
				this.ImageUri = properties["imageUri"];
				if (!string.IsNullOrWhiteSpace(this.ImageUri))
				{
					if (!this.ImageUri.StartsWith(@"http://") && !this.ImageUri.StartsWith(@"https://"))
					{
						this.ImageUri = "http://" + this.ImageUri;
					}
				}
			}

			this.IsTitleValid = true;
			this.IsImageUriValid = true;
		}

		public override EntryElement GetEntryElement()
		{
			return new EntryImageElement { Title = this.Title, ImageUri = this.ImageUri, Order = this.Order, Type = this.Type };
		}

		public override ValidationResult Validate()
		{
			ValidationResult result = new ValidationResult();
			if (this.Title.Length > EntryImageElement.MaxTitleLength)
			{
				result.AddError(Resources.EntryImageTitleTooLong, EntryImageElement.MaxTitleLength);
				this.IsTitleValid = false;
			}
			else if(string.IsNullOrWhiteSpace(this.ImageUri))
			{
				result.AddError(Resources.UriCannotBeEmpty);
				this.IsImageUriValid = false;
			}
			else if (this.ImageUri.Length > EntryImageElement.MaxUriLength)
			{
				result.AddError(Resources.UriTooLong, EntryImageElement.MaxUriLength);
				this.IsImageUriValid = false;
			}
			return result;
		}
	}
}